<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/25
 * Time: 7:28
 */
namespace App\Modules\Jobs\Services;
use App\Libs\Pay\WechatPay;
use App\Modules\Message\Services\MessageService;
use App\Modules\Order\Models\Order;
use App\Modules\Task\Models\Task;
use App\Modules\User\Models\User;
use DB;
use Illuminate\Support\Facades\Log;

class RefundService{
    /**
     * 自动退款
     */
    public static function refund() {
        $undone = DB::table('tasks as t')
            ->select('t.id','tlf.charge_fee','tlf.reward_fee','t.uid','tlf.fee')
            ->leftjoin('task_left_fees as tlf','tlf.task_id','=','t.id')
            ->where([['t.end_time','<',date('Y-m-d H:i:s')],['t.refund_status','=','NOT_REFUND'],['tlf.fee','>',0]])
            ->get();

        if($undone){
            $undone = $undone->toArray();
        }
        //var_dump(json_encode($undone,JSON_UNESCAPED_UNICODE));
        foreach ($undone as $value){
            $left_total_fee = floatval($value->fee);
            $left_charge_fee = floatval($value->charge_fee);
            $left_reward_fee = floatval($value->reward_fee);
            //var_dump($diff);
            //var_dump();
            if($left_charge_fee>=0.01 || $left_reward_fee>=0) {

                if($left_charge_fee>0) {
                    $orders = Order::where([['task_id','=',$value->id],['uid','=',$value->uid],['status','=','PAID']])->orderBy('money')->get();

                    $refund_charge_temp = $left_charge_fee;

                    $has_refund = 0;
                    //var_dump(json_encode($orders,JSON_UNESCAPED_UNICODE));
                    foreach ($orders as $item){  //遍历订单，直到退完钱
                        if($refund_charge_temp<0.01){//钱已退完，退出循环
                            break;
                        }
                        $money =($item->money - $refund_charge_temp)>=0?$refund_charge_temp:$item->money;
                        //var_dump($money);
                        $task_info = Task::getTask($item->task_id);
                        //echo $item->id.'##'.($money*100).'###'.'task:'.($task_info->title).'退款';
                        $res = WechatPay::companyPayToPersonRefund($item->id,$money*100,($task_info->title).'任务结束酬金退回');
                        //var_dump($res);
                        //var_dump($res);
                        if($res['result']){
                            DB::select("update users set estate = estate - ".$money.' where id = '.$value->uid);
                            $has_refund+=$money;
                            $refund_charge_temp-=$money;
                        }
                    }

                    try{
                        if($refund_charge_temp < 0.01){
                            //DB::select("update users set estate = estate - ".$refund_charge.' where id = '.$value->uid);
                            //DB::select('update tasks set charge_fee = charge_fee - '.$refund_charge.',fee = fee - '.$refund_charge.' where id = '.$value->id);
                            SendTemplateMessageService::SendRefundMsg($value->uid,$has_refund,$value->id,'pages/account/account');
                            Task::where('id','=',$value->id)->update(['refund_status'=>'REFUNDED']);
                        }else{
                            Task::where('id','=',$value->id)->update(['refund_status'=>'EXCEPTION']);
                            throw new \Exception('refund error:task_id:'.$value->id,304);
                        }
                        //var_dump(floatval($has_refund));
                        if(floatval($has_refund)>0){
                            DB::select("update task_left_fees set fee = fee - ".$has_refund.',charge_fee = charge_fee - '.$has_refund.' where task_id ='.$value->id);

                        }
                        if($refund_charge_temp>0){
                            User::where('id','=',$value->uid)->increment('available_estate',$refund_charge_temp);
                        }

                    }catch (\Exception $e){
                        Log::error('SendRefunsTemplateMessage failed! '.$e->getCode().$e->getMessage());
                    }
                }

                //退余额
                if(floatval($left_reward_fee)>0){
                    User::where('id','=',$value->uid)->increment('available_balance',$left_reward_fee);
                    DB::select("update task_left_fees set fee = fee - ".$left_reward_fee.',reward_fee = reward_fee - '.$left_reward_fee.' where task_id ='.$value->id );
                }
                $refund_total = floatval($left_reward_fee)+floatval($has_refund);
                if($refund_total>0) {
                    MessageService::addRefundMessage($value->uid,$refund_total,$value->id);
                }
            }
        }
    }
}